package useGenericity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UserGenericity {
    public static void main(String[] args) {
        genericityInterface3();
    }

    static void genericityDemo1(){
        //使用ArrayList时，如果不定义泛型类型时，泛型类型实际上就是Object：
        //编译器警告
        List list = new ArrayList();
        list.add("hello");
        list.add("world");

        String first = (String) list.get(0);
        String second = (String) list.get(1);

        System.out.println(first);
        System.out.println(second);
    }

    static void genericityDemo2(){
        //当我们定义泛型类型<Number>后，List<T>的泛型接口变为强类型List<Number>：
        List<String> list = new ArrayList();
        list.add("hello");
        list.add("world");

        //无需强制类型转化
        String first = list.get(0);
        String second = list.get(1);

        System.out.println(first);
        System.out.println(second);
    }

    //泛型接口
    //除了ArrayList<T>使用了泛型，还可以在接口中使用泛型。例如，Arrays.sort(Object[])可以对任意数组进行排序，但待排序的元素必须实现Comparable<T>这个泛型接口：
    static void genericityInterface(){
        String[] ss = new String[]{"Orange","Apple","Pear"};
        Arrays.sort(ss);
        System.out.println(Arrays.toString(ss));//[Apple, Orange, Pear]
    }

    static void genericityInterface2(){
        Person[] ps = new Person[]{
                new Person("Bob",61),
                new Person("Alice",99),
                new Person("Lily",87),
        };
        Arrays.sort(ps);
        System.out.println(Arrays.toString(ps));//[Apple, Orange, Pear]
    }

    static void genericityInterface3(){
        Person1[] ps = new Person1[]{
                new Person1("Bob",61),
                new Person1("Alice",99),
                new Person1("Lily",87),
        };
        Arrays.sort(ps);
        System.out.println(Arrays.toString(ps));//[Apple, Orange, Pear]
    }
}

//根据name来比较对象大小
class Person implements Comparable<Person>{
    String name;
    int score;
    Person(String name,int score){
        this.name = name;
        this.score = score;
    }
    public String toString(){
        return this.name + "," + this.score;
    }

    @Override
    public int compareTo(Person person) {
        return this.name.compareTo(person.name);
    }
}

//对象比较根据score来比
class Person1 implements Comparable<Person1>{
    String name;
    int score;
    Person1(String name,int score){
        this.name = name;
        this.score = score;
    }
    public String toString(){
        return this.name + "," + this.score;
    }

    @Override
    public int compareTo(Person1 person) {
        return this.score > person.score ? -1 : this.score == person.score ? 0 : 1 ;
    }
}